package com.web.server.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;

/**
 * @author YangJian
 * @version 1.0
 * @date 2012-5-15 下午04:28:28
 */
public class DateUtil {

    /**
     * 用时多少时间
     *
     * @param date
     * @return
     */
    public static String consumeTime(long date) {
        String str = "";

        long num = 0L;

        num = date % 1000;
        str = str + num + "毫秒";
        date = date / 1000;
        if (date > 0) {
            num = date % 60;
            str = num + "秒" + str;
            date = date / 60;
            if (date > 0) {
                num = date % 60;
                str = num + "分" + str;
                date = date / 60;
                if (date > 0) {
                    num = date % 24;
                    str = num + "时" + str;
                    date = date / 24;
                    if (date > 0) {
                        str = date + "天" + str;
                    }
                }
            }
        }
        return str;
    }

    /**
     * 将字符串转成日期
     *
     * @param date
     * @param formatStr
     * @return Date
     */
    public static Date parse(String date, String formatStr) {
        try {
            SimpleDateFormat format = new SimpleDateFormat(formatStr);
            return format.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Long nextMonth(Long mon, int flag) {
        Long res = 0L;

        Date date = mon == null ? new Date() : new Date(mon);//当前日期
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");//格式化对象
        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(date);//设置当前日期
        calendar.add(Calendar.MONTH, flag);//月份减一
        res = calendar.getTime().getTime();
        //System.out.println(sdf.format());//输出格式化的日期
        return res;
    }

    /**
     * 将日期转换成字符串
     *
     * @param date
     * @param formatStr
     * @return String
     */
    public static String format(Date date, String formatStr) {
        if(null == date){
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        return format.format(date);
    }

    /**
     * 返回当天是星期几
     *
     * @param date
     * @return 返回值从1-7，1表示星期天，7表示星期六
     */
    public static int getDayOfWeek(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);

        return calendar.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 返回当天是星期几
     *
     * @param date
     * @return 返回值从1-7，1表示星期天，7表示星期六
     */
    public static String getDayOfWeekCn(Date date) {
        int num = DateUtil.getDayOfWeek(date);

        switch (num) {
            case 1:
                return "天";
            case 2:
                return "一";
            case 3:
                return "二";
            case 4:
                return "三";
            case 5:
                return "四";
            case 6:
                return "五";
            case 7:
                return "六";
            default:
                return null;
        }

    }

    /*
     * 获取当前年份，如2013
     */
    public static int getCurrentYear() {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        return year;
    }

    /**
     * 返回一天开始的时间戳
     * @param date
     * @return
     */
    public static long getStartTime(Date date) {
        String dateStr = DateUtil.format(date, "yyyy-MM-dd");
        dateStr += " 00:00:00";
        return DateUtil.parse(dateStr, "yyyy-MM-dd HH:mm:ss").getTime();
    }

    /**
     * 返回一天结束时间的时间戳
     */
    public static long getEndTime(Date date) {
        String dateStr = DateUtil.format(date, "yyyy-MM-dd");
        dateStr += " 23:59:59.999";
        return DateUtil.parse(dateStr, "yyyy-MM-dd HH:mm:ss.SSS").getTime();
    }

    /**
     * 返回指定时间的时间戳
     */
    public static long getTime(Date date) {
        String dateStr = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        return DateUtil.parse(dateStr, "yyyy-MM-dd HH:mm:ss").getTime();
    }

    /**
     * 返回当月开始的时间
     *
     * @param date
     * @return
     */
    public static long getStartTimeOfMonth(Date date) {
        String dateStr = DateUtil.format(date, "yyyy-MM");
        return DateUtil.parse(dateStr, "yyyy-MM").getTime();
    }

    /**
     * 返回当月结束的时间
     *
     * @param date
     * @return
     */
    public static long getEndTimeOfMonth(Date date) {
        String dateStr = DateUtil.format(date, "yyyy-MM");
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        int month = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        dateStr += "-" + month + " 23:59:59.999";
        return DateUtil.parse(dateStr, "yyyy-MM-dd HH:mm:ss.SSS").getTime();
    }

    /**
     * 返回一年开始的时间戳
     *
     * @param date
     * @return
     */
    public static long getStartTimeOfYear(Date date) {
        String dateStr = DateUtil.format(date, "yyyy");
        return DateUtil.parse(dateStr, "yyyy").getTime();
    }

    /**
     * 返回一年结束的时间戳
     *
     * @param date
     * @return
     */
    public static long getEndTimeOfYear(Date date) {
        String dateStr = DateUtil.format(date, "yyyy");
        dateStr += "-12-31 23:59:59.999";
        return DateUtil.parse(dateStr, "yyyy-MM-dd HH:mm:ss.SSS").getTime();
    }


    /**
     * 返回当年开始的时间戳
     *
     * @return
     */
    public static long getStartTimeOfYear() {
        Date date = new Date();
        String dateStr = DateUtil.format(date, "yyyy");
        return DateUtil.parse(dateStr, "yyyy").getTime();
    }

    /**
     * 返回当年结束的时间戳
     *
     * @return
     */
    public static long getEndTimeOfYear() {
        Date date = new Date();
        String dateStr = DateUtil.format(date, "yyyy");
        dateStr += "-12-31 23:59:59.999";
        return DateUtil.parse(dateStr, "yyyy-MM-dd HH:mm:ss.SSS").getTime();
    }

    public static boolean isNew(long dateTime) {
        boolean flag = false;
        Date date = new Date();
        flag = date.getTime() - dateTime < 14 * 24 * 60 * 60 * 1000;
        return flag;
    }

//	// 将 日期字符串转为10位的时间戳
//	public static String getTime(String user_time) {
//		String re_time = null;
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		Date d;
//		try {
//			d = sdf.parse(user_time);
//			long l = d.getTime();
//			String str = String.valueOf(l);
//			re_time = str.substring(0, 10);
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//		return re_time;
//	}

    //将yyyy-MM-dd格式的日期字符串转为13位的时间戳
    public static long getTime2(String user_time) {
//		String re_time = null; 
        long l = 0l;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d;
        try {
            d = sdf.parse(user_time);
            l = d.getTime();
//			String str = String.valueOf(l); 
//			re_time = String.valueOf(l); 
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return l;
    }

    public static long getTime(String user_time, String format) {
        long l = 0l;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date d;
        try {
            d = sdf.parse(user_time);
            l = d.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return l;
    }

    /**
     * 以 "yyyy-MM-dd hh:mm:ss" 格式获取时间
     */
    public static long getTime(String user_time) {
        long l = 0l;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d;
        try {
            d = sdf.parse(user_time);
            l = d.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return l;
    }

    // 将10位数字的时间戳转为日期yyyyMMdd格式的整数
    public static long getStrTime(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000l));
        return Long.parseLong(re_StrTime);
    }

    /**
     * 将13位数字的时间戳转为日期yyyyMMdd格式的整数
     *
     * @param cc_time 例如：cc_time=1378224000000
     * @return
     */
    public static String getYYYY_MM_dd(Long cc_time) {
        String re_StrTime = "";
        if (cc_time == null) {
            return re_StrTime;
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            re_StrTime = sdf.format(new Date(cc_time));
            return re_StrTime;
        }
    }

    public static String getYYYY(Long cc_time) {
        String re_StrTime = "";
        if (cc_time == null) {
            return re_StrTime;
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            re_StrTime = sdf.format(new Date(cc_time));
            return re_StrTime;
        }
    }

    /**
     * 扩展 【将13位数字的时间戳转为日期yyyyMMdd格式的整数】
     *
     * @param cc_time
     * @return liuxiao
     */
    public static String getYYYY_MM_dd(String cc_time) {
        String re_StrTime = "";
        if (cc_time == null) {
            return re_StrTime;
        } else {
            Long cTime = Long.parseLong(cc_time);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            re_StrTime = sdf.format(new Date(cTime));
            return re_StrTime;
        }
    }

    public static String getYYYY_MM_dd() {
        String re_StrTime = "";
        Long cTime = new Date().getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        re_StrTime = sdf.format(new Date(cTime));
        return re_StrTime;
    }

    /**
     * 扩展 【将13位数字的时间戳转为日期yyyyMM格式的整数】
     *
     * @param cc_time
     * @return wang_huihui
     */
    public static String getYYYY_MM(String cc_time) {
        String re_StrTime = "";
        if (cc_time == null) {
            return re_StrTime;
        } else {
            Long cTime = Long.parseLong(cc_time);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            re_StrTime = sdf.format(new Date(cTime));
            return re_StrTime;
        }
    }

    public static String getYYYY_MM(Long cc_time) {
        String re_StrTime = "";
        if (cc_time == null) {
            return re_StrTime;
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            re_StrTime = sdf.format(new Date(cc_time));
            return re_StrTime;
        }
    }

    public static String getMM(String cc_time) {
        String re_StrTime = "";
        if (cc_time == null) {
            return re_StrTime;
        } else {
            Long cTime = Long.parseLong(cc_time);
            SimpleDateFormat sdf = new SimpleDateFormat("M");
            re_StrTime = sdf.format(new Date(cTime));
            return re_StrTime;
        }
    }

    public static String getMM(Long cc_time) {
        String re_StrTime = "";
        if (cc_time == null) {
            return re_StrTime;
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("M");
            re_StrTime = sdf.format(new Date(cc_time));
            return re_StrTime;
        }
    }

    public static Integer getQuarter(Long cc_time) {
        if (cc_time == null) {
            return null;
        } else {
            String re_StrTime = "";
            SimpleDateFormat sdf = new SimpleDateFormat("M");
            re_StrTime = sdf.format(new Date(cc_time));
            return Integer.parseInt(re_StrTime) % 3 == 0 ? Integer.parseInt(re_StrTime) / 3 : Integer.parseInt(re_StrTime) / 3 + 1;
        }
    }

    /**
     * 扩展 【将13位数字的时间戳转为日期yyyy-MM-dd hh:mm:ss格式的整数】
     *
     * @param cc_time
     * @return liuxiao
     */
    public static String getYYYY_MM_dd_hh_mm_ss(String cc_time) {
        String re_StrTime = "";
        if (cc_time == null) {
            return re_StrTime;
        } else {
            // 如果是mysql时间戳 长度不够十三位则后面补上000
            if (cc_time.length() == 10) {
                cc_time += "000";
            }
            Long cTime = Long.parseLong(cc_time);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            re_StrTime = sdf.format(new Date(cTime));
            return re_StrTime;
        }
    }

    public static String getYYYY_MM_dd_hh_mm_ss(Long cc_time) {
        String re_StrTime = "";
        if (cc_time == null) {
            return re_StrTime;
        } else {
            // 如果是mysql时间戳 长度不够十三位则后面补上000
            if (cc_time.toString().length() == 10) {
                cc_time *= 1000;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            re_StrTime = sdf.format(new Date(cc_time));
            return re_StrTime;
        }
    }

    /**
     * 当前季度的开始时间，即2013-01-01
     *
     * @return
     */
    public static Date getCurrentQuarterStartDate() {
//    	SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3)
                c.set(Calendar.MONTH, 0);
            else if (currentMonth >= 4 && currentMonth <= 6)
                c.set(Calendar.MONTH, 3);
            else if (currentMonth >= 7 && currentMonth <= 9)
                c.set(Calendar.MONTH, 6);
            else if (currentMonth >= 10 && currentMonth <= 12)
                c.set(Calendar.MONTH, 9);
            c.set(Calendar.DATE, 1);
            now = c.getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 当前季度的结束时间，即2013-03-31
     *
     * @return
     */
    public static Date getCurrentQuarterEndDate() {
//    	SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3) {
                c.set(Calendar.MONTH, 2);
                c.set(Calendar.DATE, 31);
            } else if (currentMonth >= 4 && currentMonth <= 6) {
                c.set(Calendar.MONTH, 5);
                c.set(Calendar.DATE, 30);
            } else if (currentMonth >= 7 && currentMonth <= 9) {
                c.set(Calendar.MONTH, 8);
                c.set(Calendar.DATE, 30);
            } else if (currentMonth >= 10 && currentMonth <= 12) {
                c.set(Calendar.MONTH, 11);
                c.set(Calendar.DATE, 31);
            }
            now = c.getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 获取上一个季度的最后一天，比如今天为20130201，则上一个季度最后一天应为20121231,注意返回的是13位的时间戳
     *
     * @return
     */
    public static long getPreviousQuarterEndDate() {
        SimpleDateFormat ymd = new SimpleDateFormat("yyyyMMdd");
        Date date = getCurrentQuarterStartDate();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, -1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        Date last = c.getTime();
//		String yyyyMMdd = ymd.format(last);
//		return Long.parseLong(yyyyMMdd);
        return last.getTime();
    }

    public static double getIncomeTax(double income) {
        double tax = 0d;
        if (income >= 800d && income < 4000d) {
            tax = (income - 800d) * 0.2;
        } else if (income >= 4000d && income < 20000d) {
            tax = income * (1 - 0.2) * 0.2;
        } else if (income >= 20000d && income < 50000d) {
            tax = income * (1 - 0.2) * 0.3 - 2000d;
        } else if (income >= 50000d) {
            tax = income * (1 - 0.2) * 0.4 - 7000d;
        }
        return tax;
    }

    /*
     * random.nextInt(max)表示生成[0,max]之间的随机数，然后对(max-min+1)取模。
	 *以生成[20,90]随机数为例，首先生成20-90的随机数，然后对(90-20+1)取模得到[0-20]之间的随机数，然后加上min=20，最后生成的是20-90的随机数
     */
    public static int getRandomData() {
        int max = 90;
        int min = 20;
        Random random = new Random();

        int s = random.nextInt(max) % (max - min + 1) + min;
        return s;
    }

    /*
     * 随机获取付款单编号
     */
    public static String getRandomIdentifier() {
        String maxIdentifier = getCurrentYear() + "" + getRandomData();
        return maxIdentifier;
    }

    /*
     * 获取昨天的时间，格式yyyy-MM-dd
     */
    public static String getYestoday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -1);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(cal.getTime());
    }

    /**
     * 判断两个时间是否在同一周
     *
     * @param firstDate
     * @param secondDate
     * @return
     * @throws ParseException
     */
    public static boolean compare(Date firstDate, Date secondDate) throws ParseException {
        /** 以下先根据第一个时间找出所在周的星期一、星期日, 再对第二个时间进行比较 */
        Calendar calendarMonday = Calendar.getInstance();
        calendarMonday.setTime(firstDate);

        boolean isFirstSunday = (calendarMonday.getFirstDayOfWeek() == Calendar.SUNDAY);

        int monday = calendarMonday.get(Calendar.DAY_OF_WEEK);   // 获取firstDate在当前周的第几天. （星期一~星期日：1~7）  
        if (isFirstSunday) {
            monday = monday - 1;
            if (monday == 0) {
                monday = 7;
            }
        }

        calendarMonday.add(Calendar.DAY_OF_MONTH, -monday + 1);   // 星期一开始时间  
        calendarMonday.set(Calendar.HOUR, 0);
        calendarMonday.set(Calendar.MINUTE, 0);
        calendarMonday.set(Calendar.SECOND, 0);

        Calendar calendarSunday = Calendar.getInstance();  // 星期日结束时间  
        calendarSunday.setTime(calendarMonday.getTime());
        calendarSunday.add(Calendar.DAY_OF_MONTH, 6);
        calendarSunday.set(Calendar.HOUR, 23);
        calendarSunday.set(Calendar.MINUTE, 59);
        calendarSunday.set(Calendar.SECOND, 59);

        // 比较第二个时间是否与第一个时间在同一周  
        if (secondDate.getTime() >= calendarMonday.getTimeInMillis() &&
                secondDate.getTime() <= calendarSunday.getTimeInMillis()) {
            return true;
        }
        return false;
    }

    /**
     * @param date
     * @return
     * @author wenjd
     * @disc 返回改日期的月份 +count个月
     */
    public static String DateJS(Date date, int count) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//格式化对象
        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(date);//设置当前日期
        calendar.add(Calendar.MONTH, count);//月份减一
        return sdf.format(calendar.getTime());//输出格式化的日期
    }

    /**
     * 在给定日期上增加x天
     *
     * @param date 原始日期
     * @param x    待增加的天数
     * @return x天后的日期
     */
    public static Date dayAfter(Date date, int x) {
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        instance.add(Calendar.DATE, x);
        return instance.getTime();
    }
}
